//
//  WebService.swift
//  PsychologicalPro
//
//  Created by 集泰 on 2017/11/24.
//  Copyright © 2017年 g-links. All rights reserved.
//

import UIKit

@objc(WebService)

class WebService: NSObject {
    class var shareInstance:WebService {
        struct Static {
            static let instance:WebService = WebService()
            
        }
        return Static.instance
    }
    
    var jwt:String?
//发送短信
    func getSmscode(phoneNo:String? ,action:String? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["phoneNo":phoneNo as AnyObject,"action":action as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            
            if (resp != nil){
                let share = ShareInfo.shareInstance

                let erro = resp!["error"] as? Int
                if erro == 0{
                    
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                }
                
            }
            
        }, parameters: params, servicePath: "/api/user/v1/smscode", methodName: "GET")
        
    }
    
//登录
    func doLogin(phoneNo:String? ,smscode:String? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["phoneNo":phoneNo as AnyObject,"smscode":smscode as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let result = resp!["result"] as? [String:AnyObject]
                    self.jwt = result!["jwt"] as? String
                    
                    UserDefaults.standard.set(self.jwt, forKey: "jwt")
                    UserDefaults.standard.synchronize()
                    
                    if self.jwt != nil && self.jwt!.count > 0 {
                        let userInfo = result!["user"] as? [String:AnyObject]
                        
                        let model = UserModel()
                        
                        model.phoneNo = userInfo!["phoneNo"] as? String
                        model.permission = userInfo!["permission"] as? String
                    }
                    
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                }
                
            }
           
        }, parameters: params, servicePath: "/api/user/v1/login", methodName: "POST")
        
    }
    
//查看活动信息状况
    func stateInfo(activityId:String?,block:@escaping (_ isSuccess:Bool, _ par:String)->Void )  {
        SVProgressHUD.show()
        
        let params:[String:AnyObject] = ["activityId":activityId as AnyObject]
        
        request(block: {(resp,error) in
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let result = resp!["result"] as? [String : AnyObject]
                    let share = ShareInfo.shareInstance
                    
                    let model = StateModel()
                    model.activityId = result?["activityId"] as? String
                    model.state2 = result?["state"] as? String
                    share.stateInfo = model

                    block(true, "")
                    return
                }else {
                    block(false, "")
                    return
                }
            }
            
        },parameters: params, servicePath: "/api/activity/info/state", methodName: "GET")
        
    }
    

    
//获取课程信息
    func activityInfo(state:String? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["state":state as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            
            if (resp != nil){
              
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let share = ShareInfo.shareInstance
                    ShareInfo.shareInstance.array11?.removeAllObjects()
                    ShareInfo.shareInstance.array22?.removeAllObjects()
                    ShareInfo.shareInstance.array33?.removeAllObjects()
                    share.array11 = NSMutableArray()
                    share.array22 = NSMutableArray()
                    share.array33 = NSMutableArray()
                    let result = resp!["result"] as? [AnyObject]
                    for mod in result!{
                        let share = ShareInfo.shareInstance
                       
                        let course = mod as? [String : AnyObject]
                        let model = MyModel()
                        model.activityId = course!["activityId"] as? String
                        model.out_trade_no = course!["out_trade_no"] as? String
                        model.imgMainUrl = course!["imgMainUrl"] as? String
                        model.title = course!["title"] as? String
                        model.fee_type = course!["fee_type"] as? String
                        model.discountedPrice = course!["discountedPrice"] as? String
                        model.activityState = course!["activityState"] as? String
                        model.time_start = course!["time_start"] as? String
                        model.activityDate = course!["date"] as? String
                        
                        
                        if model.activityState == "1"{
                            share.array11?.add(model)
                        }else if model.activityState == "2"{
                            share.array22?.add(model)
                        }else if model.activityState == "3"{
                            share.array33?.add(model)
                        }
                        
                    }
                    
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
           
            
            
        }, parameters: params, servicePath: "/api/activity/info", methodName: "GET")
        
    }
   
    //获取活动详情
    func activityDetail(activityId:String? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["activityId":activityId as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let share = ShareInfo.shareInstance
                    let result = resp!["result"] as? [String : AnyObject]
                    
                    let model = ActivityModel()
                    model.activityId = result?["activityId"] as? String
                    model.imgMainUrl = result?["imgMainUrl"] as? String
                    model.state = result?["state"] as? String
                    model.title = result?["title"] as? String
                    model.price = result?["price"] as? String
                    model.discountedPrice = result?["discountedPrice"] as? String
                    model.upperLimit = result?["upperLimit"] as! String
                    model.nPeople = result!["nPeople"] as! Int
                    model.date = result?["date"] as? String
                    model.deadline = result?["deadline"] as? String
                    model.address = result?["address"] as? String
                    
                    
                    let imgs = result!["imgs"] as? [AnyObject]
                    share.imgsArray = NSMutableArray()
                    share.imgsArray?.removeAllObjects()
                    
                    
                    for img in imgs! {
                        let share = ShareInfo.shareInstance
                        
                        let img1 = img as? [String : AnyObject]
                        let imgUrl = img1!["imgUrl"] as? [String : AnyObject]
                        
                        let modelIma = ImageModel()
                        modelIma.url = imgUrl!["url"] as? String
                        share.imgsArray?.add(modelIma)
                       
                    }
                    
                    share.modAc = model
                
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
        }, parameters: params, servicePath: "/api/activity/v1/detail", methodName: "GET")
        
    }
    
//    获取活动简略信息
    func activityBrief(pageNo:Int? ,pageSize:Int? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["pageNo":pageNo as AnyObject , "pageSize":pageSize as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
         
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let share = ShareInfo.shareInstance
                    let result = resp!["result"] as? [String : AnyObject]
                    let model = HomeModel()
                    model.pageNo = result?["pageNo"] as? Int
                    model.pageSize = result?["pageSize"] as? Int
                    
                    let data = result!["data"] as! [AnyObject]
                    share.dateArray = NSMutableArray()
                    share.dateArray?.removeAllObjects()
                    for datas in data{   
                        let data1 = datas as! [String:AnyObject]
                        let model = DataModel()
                        model.activityId = data1["activityId"] as? String
                        model.imgMainUrl = data1["imgMainUrl"] as? String
                        model.title = data1["title"] as? String
                        share.dateArray?.add(model)
                      
                    }
                
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
        }, parameters: params, servicePath: "/api/activity/v1/brief/p1", methodName: "GET")
        
    }
    
    func wechatpay(activityId:String? ,price:String? ,timeStamp:String? ,nonceStr:String? , block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["activityId":activityId as AnyObject , "price":price as AnyObject , "timeStamp":timeStamp as AnyObject ,"nonceStr":nonceStr as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let share = ShareInfo.shareInstance
                    
                    let result = resp!["result"] as? [String:AnyObject]
                    for mod in result!{
                        let pay = mod as? [String : AnyObject]
                        let model = WXApiModel()
                        model.prepay_id = pay!["prepay_id"] as? String
                        model.sign = pay!["sign"] as? String
                        model.signType = pay!["signType"] as? String
                        model.out_trade_no = pay!["out_trade_no"] as? String
                        model.time_start = pay!["time_start"] as? String
                       
                        share.pay = model
                    }
                    
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }

        }, parameters: params, servicePath: "/api/activity/pay/wechatpay/order/signup", methodName: "GET")
        
    }
//   获取轮播图
    func banner(block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
     
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
           
            if error != nil {
                block(false,"")
                return
            }
            
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let result = resp!["result"] as? [AnyObject]
                    let share = ShareInfo.shareInstance
                    share.bannerArray = NSMutableArray()
                    share.bannerArray?.removeAllObjects()
                    share.bannerImgArray = NSMutableArray()
                    share.bannerImgArray?.removeAllObjects()
                    
                    for mod in result! {
                        let share = ShareInfo.shareInstance
                        let banner = mod as! [String:AnyObject]
                        let model = BannerModel()
                        
                        
                        model.keyWord = banner["keyWord"] as? String
                        model.type = banner["type"] as? Int
                        model.updateTime = banner["updateTime"] as? String
                        share.bannerArray.add(model)

                        let mod1 = mod as? [String:AnyObject]
                        let img = mod1!["img"] as? [String:AnyObject]
                        let mod2 = BannerImgModel()
                        mod2.url = img!["url"] as? String
                        share.bannerImgArray.add(mod2.url)
                        
                    }
                    block(true,"")
                    return
             
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
            
            
        }, parameters: nil, servicePath: "/api/activity/v1/p1/banner", methodName: "GET")
        
    }
//    获取通知
    func notice(block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            if error != nil {
                block(false,"")
                return
            }
            
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let result = resp!["result"] as? [AnyObject]
                    let share = ShareInfo.shareInstance
                    share.noticeArray = NSMutableArray()
                    share.noticeArray?.removeAllObjects()
                    
                    for mod in result!{
                        let notice = mod as! [String:AnyObject]
                        let message = notice["message"] as! String
                        share.noticeArray.add(message)
                     }
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
            
            
        }, parameters: nil, servicePath: "/api/activity/v1/p1/notice", methodName: "GET")
        
    }
//    二维码
    func qrcode(activityId:String? ,block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        let params:[String : AnyObject] = ["activityId":activityId as AnyObject]   // params:参数
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let model = QrModel()
                    model.qrstr = resp!["result"] as? String
                    let share = ShareInfo.shareInstance
                    share.qrAc = model
                    
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
        }, parameters: params, servicePath: "/api/activity/qrcode", methodName: "GET")
        
    }
//    获取个人信息
    func UserInfo(block:@escaping (_ isSuccess:Bool, _ par:String)->Void ) {
        
        SVProgressHUD.show()
        
        request(block: { (resp, error) in
            SVProgressHUD.dismiss()
            
            if error != nil {
                block(false,"")
                return
            }
            if (resp != nil){
                
                let erro = resp!["error"] as? Int
                if erro == 0{
                    let share = ShareInfo.shareInstance
                    let result = resp!["result"] as? [String : AnyObject]
                    
                    let model = InfoModel()
                    
                    model.name = result!["name"] as? String
                    model.sex = result!["sex"] as? String
                    model.birthDate = result!["birthDate"] as? String
                    model.phoneNo = result!["phoneNo"] as? String

                    share.infoAc = model
                    
                    block(true,"")
                    return
                    
                }else{
                    
                    block(false,"")
                    return
                    
                    
                }
                
                
            }
            
        }, parameters: nil, servicePath: "/api/user/v1/info", methodName: "GET")
        
    }
  
    
    
    
    
    private func request(block:@escaping (_ resp:AnyObject?, _ error:NSError?)->Void, parameters:[String : AnyObject]?, servicePath:String, methodName:String ) {
        var par: [String : AnyObject]?
        par = parameters
        
        let httpClient = AFHTTPClient(baseURL: NSURL(string: HTTP_BASE_URL)! as URL)
       
        
        httpClient?.parameterEncoding = AFJSONParameterEncoding
    httpClient?.registerHTTPOperationClass(AFJSONRequestOperation.classForCoder())
        httpClient?.setDefaultHeader("Host", value: HTTP_HOST)
        httpClient?.setDefaultHeader("Accept", value: "application/json")
        if jwt != nil {
            httpClient?.setDefaultHeader("Authorization", value: "Bearer \(jwt!)")
            
            
            //            print("Bearer\(jwt)")
        }
        
        if par != nil {
            //            NSLog("request is:\n%@", parameters!)
        }else {
            par = [String : AnyObject]()
        }

        let request = httpClient?.request(withMethod: methodName, path: servicePath, parameters: par)
        
        request?.timeoutInterval = 30;
        
        let operation = httpClient?.httpRequestOperation(with: request as! URLRequest, success: { (operation, responseObject) in
            block(responseObject as AnyObject,nil)
            
        }, failure: { (operation, error) in
            
            self.errorDuringPost(resp: operation?.response, error: error as! NSError, block: block)
            
        })
        
        httpClient?.enqueue(operation)
        
    }
    
    private func errorDuringPost(resp:HTTPURLResponse?, error:NSError, block:(_ resp:AnyObject?, _ error:NSError?)->Void) {
        //        NSLog("response is:\(resp) \nerror: \(error.code), \(error.localizedDescription)")
        Utils.hideLoading()
        block(nil, error)
        Utils.showAlertMessage(errorMessage: "网络延迟，请检查网络或重试")
    }


}
